package com.way.config;

import com.way.service.MobileUserService;
import com.way.service.UserService;
import com.way.token.mobile.MobileCodeAuthenticationProvider;
import com.way.token.mobile.MobileCodeTokenGranter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 魏彪
 * http://localhost:8080/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @Autowired
    private MobileUserService mobileUserService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates);
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService)
                .tokenStore(tokenStore)
                .tokenGranter(tokenGranter(endpoints));
        // .tokenGranter();
        //.accessTokenConverter(jwtAccessTokenConverter)
        //.tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("admin")
                .secret(passwordEncoder.encode("123456"))
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(864000)
                .redirectUris("http://localhost:8081/login")
                .autoApprove(true)
                .scopes("all")
                // .authorizedGrantTypes("authorization_code");
                .authorizedGrantTypes("password", "refresh_token", "authorization_code", "mobile");
    }

    // 单点登录配置
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 获取密钥需要身份认证，使用单点登陆时必须配置
        security.tokenKeyAccess("isAuthenticated()");
    }

    /**
     * 添加自定义授权类型
     *
     * @return List<TokenGranter>
     */
    private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {

        // endpoints.getTokenGranter() 获取SpringSecurity OAuth2.0 现有的授权类型
        List<TokenGranter> granters =
                new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));

        // 构建短信验证授权类型
//        SmsCodeTokenGranter smsCodeTokenGranter =
//                new SmsCodeTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
//                        endpoints.getOAuth2RequestFactory());
//        smsCodeTokenGranter.setAccountService(accountService);
//        MobileCodeTokenGranter mobileCodeTokenGranter = new MobileCodeTokenGranter(authenticationManager,
//                endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory());

        // 向集合中添加短信授权类型
        granters.add(mobileCodeTokenGranter(endpoints));
        // 返回所有类型
        return new CompositeTokenGranter(granters);
    }

    private MobileCodeTokenGranter mobileCodeTokenGranter(AuthorizationServerEndpointsConfigurer endpoints) {
        MobileCodeAuthenticationProvider authenticationProvider = new MobileCodeAuthenticationProvider();
        authenticationProvider.setMobileUserService(mobileUserService);
        return new MobileCodeTokenGranter(authenticationProvider::authenticate, endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory());
    }

}
